﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Telerik.Web.UI;
using GPSTrackingWebsiteManager.ClassManager;

namespace GPSTrackingWebsiteManager.Manager.Pages
{
    public partial class UsersGroupsByAdminUsername : ClassManager.SessionManagerPage
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                GridSortExpression expression = new GridSortExpression();
                expression.FieldName = GPSTrackingDBV2.Entities.AdministratorsColumn.AdminUsername.ToString();
                expression.SetSortOrder("Ascending");
                this.AdminGrid.MasterTableView.SortExpressions.AddSortExpression(expression);

                expression = new GridSortExpression();
                expression.FieldName = GPSTrackingDBV2.Entities.DepartmentsColumn.Name.ToString();
                expression.SetSortOrder("Ascending");
                this.DepartmentsGrid.MasterTableView.SortExpressions.AddSortExpression(expression);

                expression = new GridSortExpression();
                expression.FieldName = "UserGroupIdSource.Name";
                expression.SetSortOrder("Ascending");
                this.UsersGroupsGrid.MasterTableView.SortExpressions.AddSortExpression(expression);

                expression = new GridSortExpression();
                expression.FieldName = GPSTrackingDBV2.Entities.UsersColumn.Username.ToString();
                expression.SetSortOrder("Ascending");
                this.UsersGrid.MasterTableView.SortExpressions.AddSortExpression(expression);
            }
        }

        protected void DepartmentsGrid_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                GetUsersGroupsByDepartmentID(GetDepartmentIdSelected());
                UsersGroupsGrid.DataBind();
                clearUsersGrid();
                resizeGrid();
            }
            catch (Exception ex)
            {
                HiddenFieldError.Value = ClassManager.CustomExceptionManager.Generate_Error(ex.Message);
                showErrorMessage("No se pudo seleccionar el departamento.");
            } 
        }

        private void GetUsersGroupsByDepartmentID(int departmentId)
        {
            try
            {
                GPSTrackingDBV2.Entities.TList<GPSTrackingDBV2.Entities.UsersGroupsByDepartments> UsersGroupsDepartmentsEntity = GPSTrackingDBV2.Data.DataRepository.UsersGroupsByDepartmentsProvider.GetByDepartmentId(departmentId);
                GPSTrackingDBV2.Data.DataRepository.UsersGroupsByDepartmentsProvider.DeepLoad(UsersGroupsDepartmentsEntity, true, GPSTrackingDBV2.Data.DeepLoadType.IncludeChildren, typeof(GPSTrackingDBV2.Entities.UsersGroups));

                UsersGroupsGrid.DataSource = UsersGroupsDepartmentsEntity;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        protected void DepartmentsGrid_NeedDataSource(object sender, Telerik.Web.UI.GridNeedDataSourceEventArgs e)
        {
            try
            {
                GetDepartmentsByAdminUsernameByCompanyID();
            }
            catch (Exception ex)
            {
                HiddenFieldError.Value = ClassManager.CustomExceptionManager.Generate_Error(ex.Message);
                showErrorMessage("No se pudo cargar el departamento.");
            }
        }

        private void GetDepartmentsByAdminUsernameByCompanyID()
        {
            try
            {
                DepartmentsGrid.DataSource = GPSTrackingDBV2Custom.Data.DataRepository.DepartmentsProvider.GetByAdminUsernameByCompanyID(GetAdminUsernameSelected(), getSessionManager().CompanyIDSelectedComboBox);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        private string GetAdminUsernameSelected()
        {
            try
            {
                foreach (GridDataItem selectedItem in AdminGrid.SelectedItems)
                {
                    return selectedItem["AdminUsername"].Text;
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return String.Empty;
        }

        protected void UsersGroupsGrid_NeedDataSource(object sender, Telerik.Web.UI.GridNeedDataSourceEventArgs e)
        {
            try
            {
                GetUsersGroupsByDepartmentID(GetDepartmentIdSelected());
            }
            catch (Exception ex)
            {
                HiddenFieldErrorUserGroups.Value = ClassManager.CustomExceptionManager.Generate_Error(ex.Message);
                showErrorMessage("No se pudo cargar los grupos de usuario.");
            }
        }

        private int GetDepartmentIdSelected()
        {
            try
            {
                foreach (GridDataItem selectedItem in DepartmentsGrid.SelectedItems)
                {
                    return int.Parse(selectedItem["DepartmentId"].Text);
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return -1;
        }

        public void showErrorMessage(string msg)
        {
            ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "objWindowsMessageManager.show_Error", "objWindowsMessageManager.show_Error('" + msg + "','Grupo Usuarios por Administrador...');", true);
        }

        protected void UsersGroupsGrid_InsertCommand(object sender, GridCommandEventArgs e)
        {
            GPSTrackingDBV2.Data.TransactionManager tm = GPSTrackingDBV2.Data.DataRepository.Provider.CreateTransaction();
            try
            {
                tm.BeginTransaction();

                int departmentIdSelected = GetDepartmentIdSelected();
                if (departmentIdSelected == -1)
                {
                    showErrorMessage("No se ha seleccionado un Departamento, debe seleccionar un departamento antes de crear un grupo de usuarios.");
                    return;
                }


                GridEditableItem item = e.Item as GridEditableItem;
                Hashtable Entity = new Hashtable();
                item.ExtractValues(Entity);

                Entity["UserGroupId"] = GPSTrackingDBV2Custom.Data.DataRepository.UsersGroupsProvider.GetNextID();

                GPSTrackingDBV2.Entities.UsersGroups UsersGroupsEntity = Invoke_EntityUserGroups(Entity);

                GPSTrackingDBV2.Data.DataRepository.UsersGroupsProvider.Insert(tm, UsersGroupsEntity);

                GPSTrackingDBV2.Entities.UsersGroupsByDepartments UsersGroupsByDepartmentsEntity = new GPSTrackingDBV2.Entities.UsersGroupsByDepartments();
                UsersGroupsByDepartmentsEntity.UserGroupId = UsersGroupsEntity.UserGroupId;
                UsersGroupsByDepartmentsEntity.DepartmentId = departmentIdSelected;

                GPSTrackingDBV2.Data.DataRepository.UsersGroupsByDepartmentsProvider.Insert(tm, UsersGroupsByDepartmentsEntity);
                tm.Commit();
            }
            catch (Exception ex)
            {
                tm.Rollback();
                HiddenFieldErrorUserGroups.Value = ClassManager.CustomExceptionManager.Generate_Error(ex.Message);
                showErrorMessage("No se pudo registrar el grupo de usuarios.");
            }  
        }

        protected void UsersGroupsGrid_UpdateCommand(object sender, GridCommandEventArgs e)
        {
            GPSTrackingDBV2.Data.TransactionManager tm = GPSTrackingDBV2.Data.DataRepository.Provider.CreateTransaction();
            try
            {
                tm.BeginTransaction();
                GridEditableItem item = e.Item as GridEditableItem;
                Hashtable Entity = new Hashtable();
                item.ExtractValues(Entity);

                GPSTrackingDBV2.Entities.UsersGroups UsersGroupsEntity = Invoke_EntityUserGroups(Entity);
                UsersGroupsEntity.OriginalUserGroupId = int.Parse(Entity["UserGroupId"].ToString());

                GPSTrackingDBV2.Data.DataRepository.UsersGroupsProvider.Update(tm, UsersGroupsEntity);
                tm.Commit();
            }
            catch (Exception ex)
            {
                tm.Rollback();
                HiddenFieldErrorUserGroups.Value = ClassManager.CustomExceptionManager.Generate_Error(ex.Message);
                showErrorMessage("No se pudo actualizar el grupo de usuarios.");
            }
        }

        protected void UsersGroupsGrid_DeleteCommand(object sender, GridCommandEventArgs e)
        {
            GPSTrackingDBV2.Data.TransactionManager tm = GPSTrackingDBV2.Data.DataRepository.Provider.CreateTransaction();
            try
            {
                tm.BeginTransaction();
                GridEditableItem item = e.Item as GridEditableItem;
                Hashtable Entity = new Hashtable();
                item.ExtractValues(Entity);

                GPSTrackingDBV2.Data.DataRepository.UsersGroupsByDepartmentsProvider.Delete(tm, int.Parse(Entity["UserGroupId"].ToString()), GetDepartmentIdSelected());

                GPSTrackingDBV2.Data.DataRepository.UsersGroupsProvider.Delete(tm, int.Parse(Entity["UserGroupId"].ToString()));
                tm.Commit();
            }
            catch (Exception ex)
            {
                tm.Rollback();
                HiddenFieldErrorUserGroups.Value = ClassManager.CustomExceptionManager.Generate_Error(ex.Message);
                if (ex.Message.Contains("FK_UsersByUsersGroups"))
                    showErrorMessage("No se puede eliminar el registro porque existen usuarios asociados al grupo de usuario que se desea eliminar, debe eliminar los usuarios asociados antes de eliminar el grupo de usuario correspondiente.");
                else
                    showErrorMessage("No se puede eliminar el registro porque esta asociados a otros registros.");
            }
        }

        private GPSTrackingDBV2.Entities.UsersGroups Invoke_EntityUserGroups(Hashtable Entity)
        {
            GPSTrackingDBV2.Entities.UsersGroups UsersGroupsEntity = new GPSTrackingDBV2.Entities.UsersGroups();
            try
            {
                UsersGroupsEntity.UserGroupId = int.Parse(Entity["UserGroupId"].ToString());
                UsersGroupsEntity.Name = Entity["UserGroupIdSource.Name"].ToString();
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return UsersGroupsEntity;
        }

        private GPSTrackingDBV2.Entities.Users Invoke_EntityUsers(Hashtable Entity)
        {
            GPSTrackingDBV2.Entities.Users UserEntity = new GPSTrackingDBV2.Entities.Users();

            try
            {
                UserEntity.Username = Convert.ToString(Entity["Username"]);
                UserEntity.Password = Convert.ToString(Entity["Password"]);
                UserEntity.Identification = Convert.ToString(Entity["Identification"]);
                UserEntity.Name = Convert.ToString(Entity["Name"]);
                UserEntity.FirstName = Convert.ToString(Entity["FirstName"]);
                UserEntity.LastName = Convert.ToString(Entity["LastName"]);
                UserEntity.Email = Convert.ToString(Entity["Email"]);
                UserEntity.Mobile = Convert.ToString(Entity["Mobile"]);
                UserEntity.Phone = Convert.ToString(Entity["Phone"]);
                UserEntity.IsActive = Convert.ToBoolean(Entity["IsActive"]);
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return UserEntity;

        }

        protected void UsersGrid_NeedDataSource(object sender, Telerik.Web.UI.GridNeedDataSourceEventArgs e)
        {
            try
            {
                GetUserByUserGroupID(GetUserGroupIdSelected());
            }
            catch (Exception ex)
            {
                HiddenFieldError.Value = ClassManager.CustomExceptionManager.Generate_Error(ex.Message);
                showErrorMessage("No se pudo cargar los usuarios.");
            } 
        }

        private int GetUserGroupIdSelected()
        {
            try
            {
                foreach (GridDataItem selectedItem in UsersGroupsGrid.SelectedItems)
                {
                    return int.Parse(selectedItem["UserGroupId"].Text);
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return -1;
        }

        private void GetUserByUserGroupID(int userGroupID)
        {
            try
            {
                UsersGrid.DataSource = GPSTrackingDBV2Custom.Data.DataRepository.UsersProvider.GetByUserGroupID(userGroupID);
            }
            catch (Exception ex)
            {
                throw ex;
            } 
        }

        protected void UsersGrid_InsertCommand(object sender, Telerik.Web.UI.GridCommandEventArgs e)
        {
            GPSTrackingDBV2.Data.TransactionManager tm = GPSTrackingDBV2.Data.DataRepository.Provider.CreateTransaction();
            try
            {
                tm.BeginTransaction();

                int userGroupIdSelected = GetUserGroupIdSelected();
                if (userGroupIdSelected == -1)
                {
                    showErrorMessage("No se ha seleccionado un Grupo de Usuario, debe seleccionar un grupo de usuario antes de crear un usuario.");
                    return;
                }

                GridEditableItem item = e.Item as GridEditableItem;
                Hashtable Entity = new Hashtable();
                item.ExtractValues(Entity);

                GPSTrackingDBV2.Entities.Users UserEntity = Invoke_EntityUsers(Entity);
                UserEntity.CompanyId = getSessionManager().CompanyIDSelectedComboBox;

                UserEntity.Password = EncryptaionManager.EncryptionManager.Encrypt(UserEntity.Password, new System.Security.Cryptography.SHA256CryptoServiceProvider());

                GPSTrackingDBV2.Entities.UsersLog usersLogEntity = new GPSTrackingDBV2.Entities.UsersLog();

                DateTime date = DateTime.Now;

                string typeUserTransaction = "";
                string usernameTransaction = "";

                if (getSessionManager().IsUser)
                {
                    typeUserTransaction = "U";
                    usernameTransaction = getSessionManager().Username;
                }
                if (getSessionManager().IsAdmin)
                {
                    typeUserTransaction = "A";
                    usernameTransaction = getSessionManager().AdminUsername;
                }
                if (getSessionManager().IsMaster)
                {
                    typeUserTransaction = "M";
                    usernameTransaction = getSessionManager().MasterUsername;
                }

                usersLogEntity.Username = UserEntity.Username;
                usersLogEntity.CompanyId = UserEntity.CompanyId;
                usersLogEntity.TransactionDate = date;

                usersLogEntity.Tick = TickManager.TickManager.GetTick(date);
                UserEntity.LastTick = usersLogEntity.Tick;

                usersLogEntity.SyncTransaction = "I";
                usersLogEntity.TypeUserTransaction = typeUserTransaction;
                usersLogEntity.CompanyIdTransaction = UserEntity.CompanyId;
                usersLogEntity.UsernameTransaction = usernameTransaction;
                //usersLogEntity.UuidTransaction
                usersLogEntity.Password = UserEntity.Password;
                usersLogEntity.Identification = UserEntity.Identification;
                usersLogEntity.Name = UserEntity.Name;
                usersLogEntity.FirstName = UserEntity.FirstName;
                usersLogEntity.LastName = UserEntity.LastName;
                usersLogEntity.CountryId = UserEntity.CountryId;
                usersLogEntity.StateId = UserEntity.StateId;
                usersLogEntity.Mobile = UserEntity.Mobile;
                usersLogEntity.Phone = UserEntity.Phone;
                usersLogEntity.IsActive = UserEntity.IsActive;
                usersLogEntity.Email = UserEntity.Email;

                GPSTrackingDBV2.Data.DataRepository.UsersProvider.Insert(tm, UserEntity);
                GPSTrackingDBV2.Data.DataRepository.UsersLogProvider.Insert(tm, usersLogEntity);

                GPSTrackingDBV2.Entities.UsersByUsersGroups UsersByUsersGroupsEntity = new GPSTrackingDBV2.Entities.UsersByUsersGroups();
                UsersByUsersGroupsEntity.UserGroupId = userGroupIdSelected;
                UsersByUsersGroupsEntity.Username = UserEntity.Username;
                UsersByUsersGroupsEntity.CompanyId = UserEntity.CompanyId;

                GPSTrackingDBV2.Data.DataRepository.UsersByUsersGroupsProvider.Insert(tm, UsersByUsersGroupsEntity);

                //GPSTrackingDBV2Custom.Data.DataRepository.UsersByCompaniesProvider.Insert(tm, UserEntity.Username, objSessionManager.CompanyIDSelectedComboBox);

                tm.Commit();
            }
            catch (Exception ex)
            {
                tm.Rollback();
                HiddenFieldError.Value = ClassManager.CustomExceptionManager.Generate_Error(ex.Message);
                if (ex.Message.Contains("PRIMARY KEY"))
                    showErrorMessage("El Usuario ya existe, debe registrar otro usuario");
                else
                    showErrorMessage("No se puede registrar el usuario.");
            }
        }

        protected void UsersGrid_UpdateCommand(object sender, Telerik.Web.UI.GridCommandEventArgs e)
        {
            GPSTrackingDBV2.Data.TransactionManager tm = GPSTrackingDBV2.Data.DataRepository.Provider.CreateTransaction();
            try
            {
                tm.BeginTransaction();
                GridEditableItem item = e.Item as GridEditableItem;
                Hashtable Entity = new Hashtable();
                item.ExtractValues(Entity);

                GPSTrackingDBV2.Entities.Users UserEntity = Invoke_EntityUsers(Entity);
                UserEntity.OriginalUsername = UserEntity.Username;
                UserEntity.CompanyId = getSessionManager().CompanyIDSelectedComboBox;
                UserEntity.OriginalCompanyId = getSessionManager().CompanyIDSelectedComboBox;
                UserEntity.Password = item.SavedOldValues["Password"].ToString();

                GPSTrackingDBV2.Entities.UsersLog usersLogEntity = new GPSTrackingDBV2.Entities.UsersLog();

                DateTime date = DateTime.Now;

                string typeUserTransaction = "";
                string usernameTransaction = "";

                if (getSessionManager().IsUser)
                {
                    typeUserTransaction = "U";
                    usernameTransaction = getSessionManager().Username;
                }
                if (getSessionManager().IsAdmin)
                {
                    typeUserTransaction = "A";
                    usernameTransaction = getSessionManager().AdminUsername;
                }
                if (getSessionManager().IsMaster)
                {
                    typeUserTransaction = "M";
                    usernameTransaction = getSessionManager().MasterUsername;
                }

                usersLogEntity.Username = UserEntity.Username;
                usersLogEntity.CompanyId = UserEntity.CompanyId;
                usersLogEntity.TransactionDate = date;

                usersLogEntity.Tick = TickManager.TickManager.GetTick(date);
                UserEntity.LastTick = usersLogEntity.Tick;

                usersLogEntity.SyncTransaction = "U";
                usersLogEntity.TypeUserTransaction = typeUserTransaction;
                usersLogEntity.CompanyIdTransaction = UserEntity.CompanyId;
                usersLogEntity.UsernameTransaction = usernameTransaction;
                //usersLogEntity.UuidTransaction
                usersLogEntity.Password = UserEntity.Password;
                usersLogEntity.Identification = UserEntity.Identification;
                usersLogEntity.Name = UserEntity.Name;
                usersLogEntity.FirstName = UserEntity.FirstName;
                usersLogEntity.LastName = UserEntity.LastName;
                usersLogEntity.CountryId = UserEntity.CountryId;
                usersLogEntity.StateId = UserEntity.StateId;
                usersLogEntity.Mobile = UserEntity.Mobile;
                usersLogEntity.Phone = UserEntity.Phone;
                usersLogEntity.IsActive = UserEntity.IsActive;
                usersLogEntity.Email = UserEntity.Email;

                GPSTrackingDBV2.Data.DataRepository.UsersProvider.Update(tm, UserEntity);
                GPSTrackingDBV2.Data.DataRepository.UsersLogProvider.Insert(tm, usersLogEntity);

                tm.Commit();
            }
            catch (Exception ex)
            {
                tm.Rollback();
                HiddenFieldError.Value = ClassManager.CustomExceptionManager.Generate_Error(ex.Message);
                showErrorMessage("No se pudo actualizar el usuario.");
            }
        }

        protected void UsersGrid_DeleteCommand(object sender, Telerik.Web.UI.GridCommandEventArgs e)
        {
            GPSTrackingDBV2.Data.TransactionManager tm = GPSTrackingDBV2.Data.DataRepository.Provider.CreateTransaction();
            try
            {
                tm.BeginTransaction();

                int userGroupIdSelected = GetUserGroupIdSelected();
                if (userGroupIdSelected == -1)
                {
                    showErrorMessage("No se ha seleccionado un Grupo de Usuario, debe seleccionar un grupo de usuario antes de eliminar un usuario.");
                    return;
                }
                GridEditableItem item = e.Item as GridEditableItem;
                Hashtable Entity = new Hashtable();
                item.ExtractValues(Entity);

                GPSTrackingDBV2.Entities.Users UserEntity = Invoke_EntityUsers(Entity);

                UserEntity.CompanyId = getSessionManager().CompanyIDSelectedComboBox;

                GPSTrackingDBV2.Entities.UsersLog usersLogEntity = new GPSTrackingDBV2.Entities.UsersLog();

                DateTime date = DateTime.Now;

                string typeUserTransaction = "";
                string usernameTransaction = "";

                if (getSessionManager().IsUser)
                {
                    typeUserTransaction = "U";
                    usernameTransaction = getSessionManager().Username;
                }
                if (getSessionManager().IsAdmin)
                {
                    typeUserTransaction = "A";
                    usernameTransaction = getSessionManager().AdminUsername;
                }
                if (getSessionManager().IsMaster)
                {
                    typeUserTransaction = "M";
                    usernameTransaction = getSessionManager().MasterUsername;
                }

                usersLogEntity.Username = UserEntity.Username;
                usersLogEntity.CompanyId = UserEntity.CompanyId;
                usersLogEntity.TransactionDate = date;
                usersLogEntity.Tick = TickManager.TickManager.GetTick(date);
                usersLogEntity.SyncTransaction = "D";
                usersLogEntity.TypeUserTransaction = typeUserTransaction;
                usersLogEntity.CompanyIdTransaction = UserEntity.CompanyId;
                usersLogEntity.UsernameTransaction = usernameTransaction;
                //usersLogEntity.UuidTransaction
                usersLogEntity.Password = UserEntity.Password;
                usersLogEntity.Identification = UserEntity.Identification;
                usersLogEntity.Name = UserEntity.Name;
                usersLogEntity.FirstName = UserEntity.FirstName;
                usersLogEntity.LastName = UserEntity.LastName;
                usersLogEntity.CountryId = UserEntity.CountryId;
                usersLogEntity.StateId = UserEntity.StateId;
                usersLogEntity.Mobile = UserEntity.Mobile;
                usersLogEntity.Phone = UserEntity.Phone;
                usersLogEntity.IsActive = UserEntity.IsActive;
                usersLogEntity.Email = UserEntity.Email;

                GPSTrackingDBV2.Data.DataRepository.UsersByUsersGroupsProvider.Delete(tm, UserEntity.Username, getSessionManager().CompanyIDSelectedComboBox, userGroupIdSelected);
                GPSTrackingDBV2.Data.DataRepository.UsersProvider.Delete(tm, UserEntity);
                GPSTrackingDBV2.Data.DataRepository.UsersLogProvider.Insert(tm, usersLogEntity);
                tm.Commit();
            }
            catch (Exception ex)
            {
                tm.Rollback();
                HiddenFieldError.Value = ClassManager.CustomExceptionManager.Generate_Error(ex.Message);
                if (ex.Message.Contains("FK_UsersByGPSGroups_Users"))
                    showErrorMessage("No se puede eliminar el usuario del grupo de usuarios porque el usuario está asociado al grupo dispositivos, debe quitar la asociación para poder eliminar el registro.");
                else
                    showErrorMessage("No se puede eliminar el usuario porque estan asociados a otros registros.");
            }
        }

        protected void UsersGroupsGrid_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                GetUserByUserGroupID(GetUserGroupIdSelected());
                UsersGrid.DataBind();
                resizeGrid();
            }
            catch (Exception ex)
            {
                HiddenFieldErrorUserGroups.Value = ClassManager.CustomExceptionManager.Generate_Error(ex.Message);
                showErrorMessage("No se puede seleccionar el grupo de usurios.");
            } 
        }

        protected void UsersGrid_ItemCommand(object sender, GridCommandEventArgs e)
        {
            if (e.CommandName == RadGrid.InitInsertCommandName)
            {
                try
                {
                    int userGroupIdSelected = GetUserGroupIdSelected();
                    if (userGroupIdSelected == -1)
                    {
                        showErrorMessage("No se ha seleccionado un Grupo de Usuario, debe seleccionar un grupo de usuario antes de crear un usuarios.");
                        resizeGrid();
                    }
                }
                catch (Exception ex)
                {
                    HiddenFieldError.Value = ClassManager.CustomExceptionManager.Generate_Error(ex.Message);
                    showErrorMessage("No se puede registrar el usuario.");
                }
            }
        }

        private void GetAdministratorsByCompanyID()
        {
            AdminGrid.DataSource = GPSTrackingDBV2Custom.Data.DataRepository.AdministratorsProvider.GetByCompanyID(getSessionManager().CompanyIDSelectedComboBox);
        }

        protected void AdminGrid_SelectedIndexChanged(object sender, EventArgs e)
        {
            GetDepartmentsByAdminUsernameByCompanyID();
            DepartmentsGrid.DataBind();
            clearUsersGroupsGrid();
            resizeGrid();
        }

        protected void AdminGrid_NeedDataSource(object sender, GridNeedDataSourceEventArgs e)
        {
            GetAdministratorsByCompanyID();
            resizeGrid();
        }

        protected void lbClearAdminGridFilters_Click(object sender, EventArgs e)
        {
            AdminGrid.MasterTableView.FilterExpression = string.Empty;

            foreach (GridColumn column in AdminGrid.MasterTableView.RenderColumns)
            {
                if (column is GridBoundColumn)
                {
                    GridBoundColumn boundColumn = column as GridBoundColumn;
                    boundColumn.CurrentFilterValue = string.Empty;
                }
            }
            AdminGrid.MasterTableView.Rebind();
            clearDepartmentsGrid();
        }

        protected void lbClearDepartmentsGridFilters_Click(object sender, EventArgs e)
        {
            DepartmentsGrid.MasterTableView.FilterExpression = string.Empty;

            foreach (GridColumn column in DepartmentsGrid.MasterTableView.RenderColumns)
            {
                if (column is GridBoundColumn)
                {
                    GridBoundColumn boundColumn = column as GridBoundColumn;
                    boundColumn.CurrentFilterValue = string.Empty;
                }
            }
            DepartmentsGrid.MasterTableView.Rebind();
            clearUsersGroupsGrid();
        }

        protected void lbClearUsersGroupsGridFilters_Click(object sender, EventArgs e)
        {
            UsersGroupsGrid.MasterTableView.FilterExpression = string.Empty;

            foreach (GridColumn column in UsersGroupsGrid.MasterTableView.RenderColumns)
            {
                if (column is GridBoundColumn)
                {
                    GridBoundColumn boundColumn = column as GridBoundColumn;
                    boundColumn.CurrentFilterValue = string.Empty;
                }
            }
            UsersGroupsGrid.MasterTableView.Rebind();
            clearUsersGrid();
        }

        protected void lbClearUserGridFilters_Click(object sender, EventArgs e)
        {
            UsersGrid.MasterTableView.FilterExpression = string.Empty;

            foreach (GridColumn column in UsersGrid.MasterTableView.RenderColumns)
            {
                if (column is GridBoundColumn)
                {
                    GridBoundColumn boundColumn = column as GridBoundColumn;
                    boundColumn.CurrentFilterValue = string.Empty;
                }
                else
                {
                    if (column is GridCheckBoxColumn)
                    {
                        GridCheckBoxColumn boundCheckColumn = column as GridCheckBoxColumn;
                        boundCheckColumn.CurrentFilterValue = "true";
                    }
                }
            }
            UsersGrid.MasterTableView.Rebind();
        }

        private void resizeGrid()
        {
            float height = float.Parse(HiddenFieldHeight.Value.ToString()) - 25;
            AdminGrid.Height = Unit.Parse((height / 2).ToString());
            DepartmentsGrid.Height = Unit.Parse((height / 2).ToString());
            UsersGroupsGrid.Height = Unit.Parse((height / 2).ToString());
            UsersGrid.Height = Unit.Parse((height - (height / 2)).ToString());
        }

        private void clearDepartmentsGrid()
        {
            DepartmentsGrid.DataSource = new string[] { };
            DepartmentsGrid.DataBind();
            clearUsersGroupsGrid();
        }

        private void clearUsersGroupsGrid()
        {
            UsersGroupsGrid.DataSource = new string[] { };
            UsersGroupsGrid.DataBind();
            clearUsersGrid();
        }

        private void clearUsersGrid()
        {
            UsersGrid.DataSource = new string[] { };
            UsersGrid.DataBind();
        }

        protected void AdminGrid_ItemCommand(object sender, GridCommandEventArgs e)
        {
            if (e.CommandName == RadGrid.SortCommandName || e.CommandName == RadGrid.FilterCommandName)
            {
                clearDepartmentsGrid();
            }
        }

        protected void DepartmentsGrid_ItemCommand(object sender, GridCommandEventArgs e)
        {
            if (e.CommandName == RadGrid.SortCommandName || e.CommandName == RadGrid.FilterCommandName)
            {
                clearUsersGroupsGrid();
            }
        }

        protected void UsersGroupsGrid_ItemCommand(object sender, GridCommandEventArgs e)
        {
            if (e.CommandName == RadGrid.SortCommandName || e.CommandName == RadGrid.FilterCommandName)
            {
                clearUsersGrid();
            }

            if (e.CommandName == RadGrid.InitInsertCommandName) {
                try
                {
                    int departmentId = GetDepartmentIdSelected();
                    if (departmentId == -1)
                    {
                        showErrorMessage("No se ha seleccionado un Departamento, debe seleccionar un departamento antes de crear un grupo de usuarios.");
                        resizeGrid();
                    }

                }
                catch (Exception ex)
                {
                    HiddenFieldErrorUserGroups.Value = ClassManager.CustomExceptionManager.Generate_Error(ex.Message);
                    showErrorMessage("No se puede eliminar el usuario porque estan asociados a otros registros.");
                }
            }
        }

        protected void UsersGrid_ItemDataBound(object sender, GridItemEventArgs e)
        {
            if (e.Item.OwnerTableView.IsItemInserted && e.Item.IsInEditMode) //item is about to be inserted  
            {
                TextBox txtid;
                GridEditableItem insertItem = (GridEditableItem)e.Item;
                txtid = (TextBox)insertItem["Password"].Controls[0];
                txtid.ReadOnly = false;
                txtid.TextMode = TextBoxMode.Password;
                txtid = (TextBox)insertItem["Username"].Controls[0];
                txtid.ReadOnly = false;
            }
            if (!(e.Item.OwnerTableView.IsItemInserted) && e.Item.IsInEditMode)   //item is about to be edit
            {
                TextBox txtid;
                GridEditableItem editItem = (GridEditableItem)e.Item;
                txtid = (TextBox)editItem["Password"].Controls[0];
                txtid.TextMode = TextBoxMode.Password;
                txtid.ReadOnly = true;
                txtid = (TextBox)editItem["Username"].Controls[0];
                txtid.ReadOnly = true;
            }  
        }
        
        protected SessionManager getSessionManager() {
            return (SessionManager)HttpContext.Current.Session["SessionManager"];
        }

        protected void lbShowError_Click(object sender, EventArgs e)
        {
            showErrorMessage(HiddenFieldError.Value);
        }

        protected void lbShowErrorUserGroups_Click(object sender, EventArgs e)
        {
            showErrorMessage(HiddenFieldErrorUserGroups.Value);
        }

    }
}